package com.tmc.service.intcar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.dao.impl.intcar.IntcarDriverDaoImpl;
import com.tmc.dao.impl.intcar.IntcarOrderDaoImpl;
import com.tmc.entity.intcar.IntcarDriver;
import com.tmc.entity.intcar.IntcarOrder;
import com.tmc.util.ObjectUtil;


/**
 * @author zhang
 * @date 2017年12月27日 下午3:22:00 
 */
@Service
@Transactional
public class IntcarDriverServiceImpl {
	
	private Log log = LogFactory.getLog(IntcarDriverServiceImpl.class);
	
	@Autowired
	private IntcarDriverDaoImpl driverDao;
	
	@Autowired
	private IntcarOrderDaoImpl orderDao;
	
	public CommonResult save(ContextInfo context, IntcarDriver driver){
		IntcarOrder order = orderDao.getById(driver.getOrderID());
		if(order == null){
			return CommonResult.makeFail("ID为" + driver.getOrderID() + "不存在订单！");
		}
		CommonResult check = check(driver);
		if(!check.isSuccess()){
			return check;
		}
		IntcarDriver dbDriver = null;
		if(driver.getDriverID() != null){
			dbDriver = driverDao.getById(driver.getDriverID());
		}else if(driver.getOrderID() != null){
			dbDriver = driverDao.getByOrderID(context, driver.getOrderID());
		}
		if(dbDriver == null){
			//新增
			ObjectUtil.setBaseInfo(driver, context);
			driverDao.insert(driver);
		}else{
			//更新
			try {
				ObjectUtil.copyProperties(order, dbDriver, new String[]{"createdBy", 
						"creationDate", "enabledFlag", "driverID" , "orderID"});
				ObjectUtil.updateBaseInfo(dbDriver, context);
				driverDao.update(dbDriver);
			} catch (Exception e) {
				log.error("拷贝对象出错！", e);
				return CommonResult.makeFail("拷贝对象出错！");
			} 
		}
		return CommonResult.makeSuccess();
	}
	
	private CommonResult check(IntcarDriver driver){
		if(ObjectUtil.noText(driver.getDriverName())){
			return CommonResult.makeFail("司导姓名不能为空！");
		}
		if(ObjectUtil.noText(driver.getDriverCarDesc())){
			return CommonResult.makeFail("司导手机号码不能为空！");
		}
		return CommonResult.makeSuccess();
	}
}
